Learning Flex Basics (Part 2): Creating a Simple Calculator with Macromedia Flex
Table of Contents
- Introduction
- Building the Calculator
- Create the Application Object
- Add a Panel for the Calculator
- Add the Calculator Display
- Add a Grid to Lay Out the Buttons
- Add the Calculator Buttons
- Create the CalculatorController Class
- Add Properties to the Controller Class
- Add Controller Methods
- Instantiate the CalculatorController Class
- Complete Code Listing for calculator.mxml
- Complete Code Listing for CalculatorController.as
- Where to Go From Here
Add Properties to the Controller Class
If you review the values you set for the click events on the calculator buttons, you will see that you need the following public methods in the controller:
doOperationaddNumberclearEntryclearAllsetOperation
You will also create three private methods that the controller uses internally:
setDisplaysetCurrentRegisterresetAfterOp
The general syntax for methods is:
[public|private] function methodName(parameter1:dataType...):returnDataType
{
[ActionScript statements]
}
None of the controller methods will return values, so the return data type will be Void for each of them.
Add the doOperation() Method
The doOperation() method performs addition, subtraction,
multiplication, or division depending on which operation the user requests.
Before carrying the operation, set the r1 and r2 properties equal
to the reg1 and reg2 values, respectively, cast to the Number data type
using the Number() method, built into ActionScript.
To choose the appropriate operation, you will use a switch-case construct. The general syntax for switch-case in ActionScript is:
switch (expression)
{
case value:
[ActionScript statements]
break; // without this you fall through to next case
[more cases]
default:
[default case actions]
}
The other bit of ActionScript, the operators for addition, subtraction, multiplication, and division are (and you can probably guess):
+-*/
Use the following steps to add the operation() method.
-
After the constructor method, create a public
doOperationmethod that takes no parameters and returns nothing:public function doOperation():Void { } -
At the beginning of the method block, set
this.r1andthis.r2equal to the respective values ofreg1andreg2cast to the Number type:this.r1=Number(reg1); this.r2=Number(reg2);
-
Add a switch-case structure that switches on the value of the
operationproperty:switch (operation) { } -
Inside the switch block, add four cases for the operation types:
add,subtract,multiply, anddivide. In the each case, set the result property equal to the appropriate operation onr1andr2,then call theresetAfterOp()method, and close each case with abreakstatement:case "add": this.result=r1+r2; resetAfterOp(); break; case "subtract": this.result=r1-r2; resetAfterOp(); break; case "multiply": this.result=r1*r2; resetAfterOp(); break; case "divide": this.result=r1/r2; resetAfterOp(); break;
-
Add a
defaultcase that does nothing (in case no operation is set):default: // do nothing
Add the addNumber() Method
The addNumber() method will take a number in string form passed from the
calculator view and append it to the string value for the current register.
The + operator in ActionScript is overloaded (the only operation that is)
and performs string concatenation if both the operands are strings.
The concatenation is simple, but the method needs to take care of a couple of a special case: After the method performs the operation, it copies the result to register 1, and sets register 2 as the current register in case the user wants to perform further operations on the result. If the user starts entering numbers rather than setting a new operation, however, you clear register 1 and set it as the current register.
To check for this condition and perform the correct action, you must use
an if structure.
You will also need to check two conditions, so you need to know that the
logical AND operator in ActionScript is && (the
logical OR operator is || ). The general syntax for if-else structures
is:
if (condition[s])
{
[ActionScript statements]
}[else if (condition) // 0 or more
{
[ActionScript statements]
}else // 0 or one
{
[ActionScript statements]
}]
The comparison operators for ActionScript are common ones:
| Operator | Meaning |
|---|---|
| == | equals |
| < | less than |
| > | greater than |
| <= | less than or equal |
| >= | greater than or equal |
| ! | logical NOT |
An additional ActionScript concept you need for this method is dynamic evaluation.
Modify the current register, keeping in mind which register is
current is set at runtime by the setCurrentRegister() method
you will create later. The currentRegister property will always be equal
to the name of one of the register properties, either reg1 or reg2,
so you can get the current register using the expression this[currentRegister].
Square brackets following an object reference forces dynamic evaluation,
and so you can use them to dynamically set or retrieve a property name.
-
After the
doOperation()method, create a publicaddNumber()method that takes a String parameter called n and returns nothing:public function addNumber(n:String):Void { } -
Inside the method block, add an
ifstructure that checks for the conditions that theoperationproperty is equal to "none" and thecurrentRegisterproperty is equal to "reg2":if (operation=="none" && currentRegister=="reg2") { }Note: These conditions are true if the
doOperation()called theresetAfterOp()method, and if the user has clicked a number button. -
Inside the if block, set the reg1 property equal to an empty string and then call the
setCurrentRegister()method (which you create later):reg1=""; setCurrentRegister();
-
After the if structure, append n to the value of the current register:
this[currentRegister]+=n;
Note that you are using a shortcut common to several programming languages here. The statement above is the equivalent of
this[currentRegister] = this[currentRegister] + n; -
Add a call to the
setDisplay()method, passing the currentRegister property as an argument (you create this method later):setDisplay(currentRegister);
Add the clearEntry() and clearAll() Methods
These two methods are similar and straightforward, so you'll do them together.
For the
clearEntry() method, clear the current register and the display.
For the clearAll() method, clear both registers and the display,
set the pending operation to none,
and set the currentRegister property to reg1.
-
Add a public
clearEntry()method that takes no parameters and returns nothing:public function clearEntry():Void { } -
In the method block, set the value of the current register to an empty string and then call the
setDisplay()method, passing thecurrentRegisterproperty as an argument:this[currentRegister]=""; setDisplay(currentRegister);
-
Add a public
clearAll()method that takes no parameters and returns nothing:public function clearAll():Void { } -
In the method block, set both register values to empty strings, and then call
setCurrentRegister(), passing nothing, callsetOperation, passing "none," and callsetDisplay, passingcurrentRegister:reg1=""; reg2=""; setCurrentRegister(); setOperation("none"); setDisplay(currentRegister);
Add setOperation() Method
This is a straightforward setter method. After setting the pending operation,
reset the current register using a setCurrentRegister() method that you will
create later in the tutorial.
-
Add a public
setOperation()method that takes a parameter calledoperationof typeStringand returns nothing:public function setOperation(operation:String):Void { } -
In the method block, set the value of the
operationproperty to the passed operation parameter and then call thesetCurrentRegister()method:this.operation=operation; setCurrentRegister();
Add setDisplay(), setCurrentRegister(), and resetAfterOp() Methods
The three private methods are also straightforward.
The setDisplay() method sets the text property of the calculator display label to the value
of the register whose name is passed as a parameter. The setCurrentRegister() method sets
register 1 as current if it is empty, and otherwise sets register 2 as current. The resetAfterOp() method copies the result of an operation to register 1 and sets other values to prepare
for further operations.
-
Add a private
setDisplay()method that takes a parameter calledregisterof typeStringand returns nothing:private function setDisplay(register:String):Void { } -
In the method block, set the value of the
calcView.calcDisplay.textproperty to the passed register parameter:calcView.calcDisplay.text = this[register];
-
Add a private
setCurrentRegister()method that takes no parameters and returns nothing:private function setCurrentRegister():Void { } -
In the method block, create an
if-elsestructure that sets thecurrentRegisterproperty to reg1 if reg1's current value is an empty string, and setscurrentRegisterto reg2 otherwise:if (reg1=="") { currentRegister="reg1"; } else { currentRegister="reg2"; } -
Add a private
resetAfterOp()method that takes no parameters and returns nothing:private function resetAfterOp():Void { } -
In the method block, set the value of
reg1to the current value ofresult, setsreg2to an empty string, callssetDisplay(), passing reg1 as the argument, and callssetOperation(), passing none as the argument:reg1=String(result); reg2=""; setDisplay("reg1"); setOperation("none"); Save the file.
Note: This completes the CalculatorController.as file.